import os
import time
from comm.functons import md5


class CacheManager:
    def __init__(self):
        self.base_path = os.path.join(os.path.dirname(__file__), '../cache')
        if not os.path.exists(self.base_path):
            os.makedirs(self.base_path)

    def _fix_path(self, key):
        key = md5(key)
        file_path = f'{self.base_path}/{key}.html'
        print(file_path)
        return file_path

    def get(self, key):
        file_path = self._fix_path(key)
        if not os.path.exists(file_path):
            return
        if time.time() - os.stat(file_path).st_mtime < 86400:
            with open(file_path, 'r', encoding='utf-8') as fp:
                return fp.read()
        os.unlink(file_path)
        return

    def set(self, key, value):
        file_path = self._fix_path(key)
        with open(file_path, 'w', encoding='utf-8') as fp:
            fp.write(value)


if '__main__' == __name__:
    # r = os.path.getmtime('../cache/7fe96495ea8842f1afdaf29dc4dfb2a1.html')
    # print(time.time() - r)
    # r = os.stat('../cache/7fe96495ea8842f1afdaf29dc4dfb2a1.html')
    # print(r.st_ctime)  # 创建时间
    # print(r.st_mtime)  # 最后一次修改的时间

    cm = CacheManager()
    print(cm.get('1'))
    # print(cm.set('1', '2'))
